<?php

namespace App\Services\Platform\Doc;

use App\Services\ServiceTrait;
use App\Exceptions\Response\ServiceException;
use App\Mappers\Platform\Doc\TreeMapper;
use App\Models\Game\Platform\Doc\Tree;
use App\Models\Game\Platform\Doc\Doc;

class TreeService
{
    use ServiceTrait;


    /**
     * 创建数据
     *
     * @param \Illuminate\Http\Request $request
     * @return \App\Models\Game\Platform\Doc\Tree
     */
    public function store($request)
    {
        // 事物回滚
        $tree = Tree::dbConnection()->transaction(function () use ($request) {
            // 创建节点
            $tree = Tree::create(
                TreeMapper::make($request)->toArray()
            );
            // 父级节点
            $parent = Tree::firstOrNew(['id' => $tree->parent_id], ['path' => '0']);
            // 更新关联字段
            $tree->sort = $tree->id;
            $tree->path = $parent->path . '.' . $tree->id;
            $tree->save();

            return $tree;
        });

        return $tree;
    }

    /**
     * 更新数据
     *
     * @param int $id
     * @param \Illuminate\Http\Request $request
     * @return \App\Models\Game\Platform\Doc\Tree
     */
    public function update($id, $request)
    {
        // 树节点
        $tree = Tree::findOrFail($id);
        // 修改数据
        $tree->fill(
            TreeMapper::make($request)->toArray()
        );
        // 保存数据
        $tree->save();

        return $tree;
    }

    /**
     * 删除数据
     *
     * @param int $id
     * @return \App\Models\Game\Platform\Doc\Tree
     * @throws ServiceException
     */
    public function destroy($id)
    {
        // 有无子节点
        if (Tree::where('parent_id', $id)->exists()) {
            throw new ServiceException(ServiceException::SERVICE_EXISTED_ORG_CHILDREN);
        }
        // 树节点
        $tree = Tree::findOrFail($id);

        // 删除文档
        Doc::where('tree_id', $id)->delete();

        // 删除节点
        $tree->delete();

        return $tree;
    }
}
